﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Security.Cryptography;
using NTTHAO.CommonWeb;
using NTTHAO.Web.BL.Authentication;
using NTTHAO.Sites.CommonSite;

public partial class Sites_KienTrucMoi_Webparts_User_Login : NTTHAO.CommonWeb.CommonUserControl
{
    private static string CHALLENGE_SESSION_KEY = "CHALLENGE_SESSION_KEY";
    public string _ErrorString = "";

    public bool IsAuthenticated
    {
        get
        {
            return Authentication.IsAuthenticated;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            string action = Request.QueryString["action"];
            string jsonResult = "{}";

            if ("logout".Equals(action, StringComparison.OrdinalIgnoreCase))
            {
                Authentication.SignOut();
                jsonResult = "{\"result\":\"OK\", \"message\":\"Đăng xuất thành công.\"}";
            }
            else
            {
                string user = Request.QueryString["value"];
                string pass = Request.QueryString["pass"];

                user = user == null ? "" : user.Trim();
                pass = pass == null ? "" : pass.Trim();

                bool serviceOK = this.Login(user, pass);

                if (serviceOK)
                {
                    jsonResult = "{\"result\":\"OK\", \"message\":\"Đăng nhập thành công.\"}";
                }
                else
                {
                    jsonResult = "{\"result\":\"NG\", \"message\":\"Tên đăng nhập hay mật khẩu không đúng.\"}";
                }
            }

            Response.ClearContent();
            Response.HeaderEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/html";
            Response.Write(jsonResult);
        }
        catch (Exception ex) 
        {
            Response.ClearContent();
            Response.HeaderEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/html";
            Response.Write(ex.Message);
        }
    }

    public bool Login(string userName, string pass)
    {
        try
        {
            User user = new User(userName.Trim());
            if (user.ID > 0)
            {
                if (user.Password.Equals(pass.Trim(), StringComparison.OrdinalIgnoreCase))
                {
                    Authentication.SetAuthCookie(user.UserName, false);

                    user.LastLoginTime = DateTime.Now;
                    user.Update();

                    return true;
                }
            }
        }
        catch { }

        return false;
    }
}
